const puppeteer = require('puppeteer')

let browser
let requestCount = 0
const MAX_REQUESTS_PER_BROWSER = 50

async function getBrowser() {
  if (!browser || requestCount >= MAX_REQUESTS_PER_BROWSER) {
    if (browser) {
      await browser.close()
    }
    browser = await puppeteer.launch({
      headless: 'new',
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    })
    requestCount = 0
  }
  return browser
}

/**
 * 解析视频真实直链
 * @param {string} targetUrl - 短视频页面链接
 * @returns {Promise<{title: string, videoSrcs: string[]}>}
 */
async function parseVideoRealUrl(targetUrl) {
  if (!targetUrl || !targetUrl.startsWith('http')) {
    throw new Error('缺少或无效的 URL 参数')
  }

  const browser = await getBrowser()
  const page = await browser.newPage()

  try {
    await page.goto(targetUrl, { waitUntil: 'networkidle2', timeout: 60000 })

    // 等待视频 source
    await page.waitForSelector('video source', { timeout: 10000 })

    const title = await page.title()
    const videoSrcs = await page.$$eval('video source', nodes =>
      nodes.map(n => n.src).filter(Boolean)
    )

    requestCount++

    return { title, videoSrcs }
  } finally {
    await page.close()
  }
}

module.exports = { parseVideoRealUrl }